package top.lcpsky.flashcards.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;
import top.lcpsky.flashcards.entity.Market;
import top.lcpsky.flashcards.entity.Shares;
import top.lcpsky.flashcards.entity.SharesDaily;
import top.lcpsky.flashcards.util.Converts;
import top.lcpsky.flashcards.util.DatePattern;
import top.lcpsky.flashcards.util.Dates;

@Slf4j
@Service
public class NeteasySharesRepository {

	public static final String NETEASY_API_URL = "http://quotes.money.163.com/service/chddata.html?code=%s&start=%s&end=%s&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;VOTURNOVER;VATURNOVER";
	
	private RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());

	
	/**
	 * 获取网易的股票信息，返回的是cvs文件
	 * @param code 0代表sh，1代表sz
	 * @param start
	 * @param end
	 * @return
	 * @throws ParseException 
	 */
	public List<SharesDaily> remoteGetSharesDaily(String code, Date start, Date end) throws ParseException {
		List<SharesDaily> dailies = Lists.newArrayList();
		String url = String.format(NETEASY_API_URL, code, Dates.format(start, DatePattern.NO_LINE_DATE), Dates.format(end, DatePattern.NO_LINE_DATE));
		log.debug("网易请求股票信息：" + url);
		ResponseEntity<byte[]> resp = restTemplate.getForEntity(url, byte[].class);
		try (ByteArrayInputStream input = new ByteArrayInputStream(resp.getBody());) {
			// csv文件，直接按文本行读取
			List<String> lines = IOUtils.readLines(input, "GBK");
			// 去掉标题行
			lines.remove(0);
			if (!CollectionUtils.isEmpty(lines)){
				// 股票信息
				Shares shares = new Shares();
				shares.setName(lines.get(0).split(",")[2]);
				shares.setCode(StringUtils.substring(code, 1));
				// 网易code第一位是市场，1是深市，0是上海
				int marketCode = Converts.toInt(StringUtils.substring(code, 0, 1));
				shares.setMarket(Market.of(marketCode));
				double maxPrice = 0;
				for (String line : lines) {
					String[] cells = StringUtils.split(line, ",");
					SharesDaily daily = new SharesDaily();
					daily.setDay(Converts.toDate(cells[0]));
					daily.setEndPrice(Converts.toDouble(cells[3]));
					daily.setMaxPrice(Converts.toDouble(cells[4]));
					daily.setMinPrice(Converts.toDouble(cells[5]));
					daily.setStartPrice(Converts.toDouble(cells[6]));
					daily.setLastDayEndPrice(Converts.toDouble(cells[7]));
					daily.setUpDownAmount(Converts.toDouble(cells[8]));
					daily.setUpDownRate(Converts.toDouble(cells[9]));
					daily.setTradeNum(Converts.toLong(cells[10]));
					daily.setTradeAmount(Converts.toLong(cells[11]));
					daily.setShares(shares);
					if (maxPrice < daily.getEndPrice()) {
						maxPrice = daily.getEndPrice();
					}
					dailies.add(daily);
				}
				shares.setMaxPrice(maxPrice);
				shares.setSalePrice(maxPrice * 0.9);
			}
		} catch (IOException e) {
			throw new RuntimeException("读取文件失败", e);
		}
		return dailies;
	}
}
